﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Linq;
using METODESA.Server.Data.Exceptions;
using METODESA.Server.Data.METODESA.Entity;
using METODESA.Server.Data.METODESA.Factorys;
using METODESA.Server.Data.METODESA.Nhibernate;
using Metodesa.Logic;
using Metodesa.Tools;

namespace Metodesa.Views.Home
{
    public partial class ListCliente : Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ValidatorCedula1.ValidationExpression.Equals(""))
            {
                loadExpressions();
            }
            if (ValidatorCedula1.ErrorMessage.Equals(""))
            {
                loadMessages();
            }


            label.Visible = false;
            ListClientes.Visible = false;
            PanelAddCliente.Visible = false;
            PanelEditCliente.Visible = false;
            if (Session["User"] != null)
            {
                Empleado usuario = (Empleado)Session["User"];
            }
            else
            {
                Response.Redirect("../../Views/Home/Index.aspx", true);
            }

            int ids = -1;


            String action = Request.QueryString.Get("a");

            if (action != null)
            {

                if (action.Equals("s")) // Select for update
                {
                    prepareDetailsUpdate();  //Preparo el panel para hacer Update
                }
                else if (action.Equals("d"))
                {
                    // DELETE

                    try
                    {
                        ids = int.Parse(Request.QueryString.Get("id"));

                        ClienteLogic.delete(ids);
                        
                        label.Visible = true;
                        label.ForeColor = Color.Blue;
                        label.Text = "Cliente eliminado satifactoriamente";
                    }
                    catch (EntityCouldntBeDeleted exception)
                    {
                        Session.Add("Error", exception);
                        label.Visible = true;
                        label.ForeColor = Color.Red;
                        label.Text = "No se pudo eliminar el cliente";
                    }
                    catch (Exception exception)
                    {
                        Session.Add("Error", exception);
                        Response.Redirect("../../Views/Home/Error.aspx", true);
                    }
               
                }

            }
            else
                PanelEditCliente.Visible = false;

        }

        private void loadMessages()
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                string path = Path.Combine(Server.MapPath("~"), @"Messages.xml");
                xDoc.Load(path);

                XmlNodeList lista = xDoc.GetElementsByTagName("message");
                foreach (XmlElement element in lista)
                {
                    if (element.GetAttribute("name").Equals("requeridoNombre"))
                    {
                        RequiredFieldNombre1.ErrorMessage = element.GetAttribute("error");
                        RequiredFieldNombre2.ErrorMessage = element.GetAttribute("error");
                    }
                    else if (element.GetAttribute("name").Equals("requeridoApellido"))
                    {
                        RequiredFieldApellido1.ErrorMessage = element.GetAttribute("error");
                        RequiredFieldApellido2.ErrorMessage = element.GetAttribute("error");
                    }
                    else if (element.GetAttribute("name").Equals("requeridoCedula"))
                    {
                        RequiredFieldCedula1.ErrorMessage = element.GetAttribute("error");
                        RequiredFieldCedula2.ErrorMessage = element.GetAttribute("error");
                    }
                    else if (element.GetAttribute("name").Equals("formatoCedula"))
                    {
                        ValidatorCedula1.ErrorMessage = element.GetAttribute("error");
                        ValidatorCedula2.ErrorMessage = element.GetAttribute("error");
                    }
                }
            }catch(Exception exception)
            {
                Session.Add("Error", exception);
                Response.Redirect("../../Views/Home/Error.aspx", true);
                
                
            }
        }
        private void loadExpressions()
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                string path = Path.Combine(Server.MapPath("~"), @"Validations.xml");
                xDoc.Load(path);

                XmlNodeList lista = xDoc.GetElementsByTagName("validation");
                foreach (XmlElement element in lista)
                {
                    if (element.GetAttribute("name").Equals("cedula"))
                    {
                        ValidatorCedula1.ValidationExpression = element.GetAttribute("expression");
                        ValidatorCedula2.ValidationExpression = element.GetAttribute("expression");
                    }
                }
            }
            catch (Exception exception)
            {
                Session.Add("Error", exception);
                Response.Redirect("../../Views/Home/Error.aspx", true);

            }
        }


        private void prepareDetailsUpdate() // Metodo para preparar el panel de detalles para hacer el Update
        {
            int ids;
            PanelAddCliente.Visible = false;
            PanelEditCliente.Visible = true; // Hacer Visible el panel de detalles
            ids = int.Parse(Request.QueryString.Get("id"));
            Cliente cliente = ClienteDao.getClienteById(ids); // Busco la instalacion seleccionado por codigo
            teId.Text = ids.ToString();
            teName.Text = cliente.Nombre;
            teLastName.Text = cliente.Apellido;                // Asigno todos los textBox los valores q tiene el cliente
            teCi.Text = cliente.CedulaRif;
            teAddress.Text = cliente.Direccion;

        }

        private void EditCliente()
        {

            PanelEditCliente.Visible = false;
            PanelAddCliente.Visible = false;

            try
            {
                ClienteLogic.update(int.Parse(teId.Text), teName.Text, teLastName.Text, teCi.Text, teAddress.Text);

                label.Visible = true;
                label.ForeColor = Color.Blue;
                label.Text = "Cliente mofificado satifactoriamente";
            }
            catch (EntityCouldntBeUpdated exception)
            {
                Session.Add("Error", exception);
                label.Visible = true;
                label.ForeColor = Color.Red;
                label.Text = "No se pudo modificar el cliente";
                PanelEditCliente.Visible = true;
            }
            catch (Exception exception)
            {
                Session.Add("Error", exception);
                Response.Redirect("../../Views/Home/Error.aspx", true);


            }
        }

        private void prepareDetailsAdd()
        {
            ListClientes.Visible = false;
            PanelAddCliente.Visible = true;

            taName.Text = "";
            taLastName.Text = "";
            taCi.Text = "";
            taAddress.Text = "";
        }

        private void AddCliente()
        {
            PanelAddCliente.Visible = false;
            PanelEditCliente.Visible = false;

            Session.Add("field", null);
            Session.Add("selected", null);

            try
            {
                
                ClienteLogic.save(taLastName.Text, taCi.Text, taAddress.Text, taName.Text);
                label.Visible = true;
                label.ForeColor = Color.Blue;
                label.Text = "Cliente agregado satifactoriamente";

            }
            catch(EntityCouldntBeSaved)
            {
                label.Visible = true;
                label.ForeColor = Color.Red;
                label.Text = "No se pudo agregar el cliente";
                PanelAddCliente.Visible = true;
            }
            catch(Exception e)
            {   
                Session.Add("Error",e);
                Response.Redirect("../../Views/Home/Error.aspx", true);
            }
           
        }

        protected void PrepareAddButton_Click(object sender, EventArgs e)
        {
            prepareDetailsAdd();
        }

        protected void EditButton_Click(object sender, EventArgs e)
        {
            EditCliente();
        }

        protected void AddButton_Click(object sender, EventArgs e)
        {
            AddCliente();
        }

        protected void FindButton_Click(object sender, EventArgs e)
        {
            IList<Cliente> lista;
            if (option != null && option.SelectedItem != null)
                lista = ClienteLogic.processSearch(searchbox.Text, option.SelectedValue);
            else
                lista = ClienteLogic.processSearch(searchbox.Text, "");

            HtmlTable table = ClientesTools.ListClientes(lista);


            if (table != null)
            {
                ListClientes.Controls.Add(table);
                ListClientes.Visible = true;
            }
            else
            {
                label.Visible = true;
                label.ForeColor = Color.DarkRed;
                label.Text = "No se encontraron clientes que cumplan con la búsqueda";
            }
        }


    }

}
